//修改模板
import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Modal, Icon, Tag} from 'antd';
import money from '../image/u1985.png';
import app from '../AppMethod';
import {user, wechat, order} from "../value";
import camera from '../image/camera.png';
import {config} from "../config";

const FormItem = Form.Item;

//选择跟车人
class ChooseXh extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            editVisible: false,
            editConfirmLoading: false,
            roleData: [],
            type: this.props.type,
            chooseData: []
        }
    };

    render() {
        return (
            <span>
                <Button style={{marginLeft: '0px'}} type="default" size="small"
                        onClick={() => this.setModalVisible(true)}>
                    <Icon type="plus" style={{fontSize: 12}}/>
                </Button>
                <Row>
                    <Modal
                        maskClosable={false}
                        visible={this.state.editVisible}
                        editConfirmLoading={this.state.editConfirmLoading}
                        title="选择跟车人"
                        wrapClassName="vertical-center-modal"
                        width="600px"
                        onCancel={() => this.setModalVisible(false)}
                        footer={[
                            <Button key="back" type='default' onClick={() => {
                                this.setModalVisible(false)
                            }}>取消</Button>,
                            <Button key="submit" type="primary" onClick={() => {
                                this.clickOk()
                            }}>确定</Button>
                        ]}
                    >
                    <div className="clearfix">
                        {
                            this.state.roleData.map((item, index) => {
                                return (
                                    <span key={index} className={item.is_choose == true ? "roleItem1" : "roleItem"}
                                          onClick={() => this.chooseRole(index)}>
                                        {item.employee_name}
                                    </span>
                                )
                            })
                        }
                    </div>
                </Modal>
                </Row>
            </span>
        )
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    setModalVisible(visible) {
        if (visible) {
            this.handleGetEmployee();
        }
        this.setState({
            editVisible: visible
        })
    };

    /**
     * 查询跟车负责人列表
     */
    handleGetEmployee() {
        app.post(user.SEARCH_DUTYEMPLOYEE, {duty_type: '3'}).then((result) => {
            if (result.code === 1) {
                let roleData = result.data.dataSet;
                let data = [];
                for (let i = 0; i < roleData.length; i++) {
                    let item = {};
                    item.employee_id = roleData[i].employee_id;
                    item.employee_name = roleData[i].employee_name;
                    data.push(item);
                }
                this.setState({roleData: data});
            } else {
                this.setState({roleData: []})
            }
        })
    }

    /**
     * 处理选择负责人事件
     * @param index
     */
    chooseRole(index) {
        let data = this.state.roleData;
        let is_choose = !data[index].is_choose;
        data[index].is_choose = is_choose;
        this.setState({roleData: data});
    }

    /**
     * 处理确定负责人事件
     */
    clickOk() {
        let data = this.state.roleData;
        let newData = [];
        for (let i = 0; i < data.length; i++) {
            if (data[i].is_choose == true) {
                newData.push(data[i]);
            }
        }
        this.props.choose(newData);
        this.setState({editVisible: false});
    }
};
const ChooseXhs = Form.create()(ChooseXh);

//选择车牌号
class ChooseCar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editVisible: false,
            editConfirmLoading: false,
            roleData: [],
            type: this.props.type,
            chooseData: {},
            is_choose: -1,
        }
    };

    render() {
        return (
            <span>
                <a onClick={() => this.setModalVisible(true)}>选择</a>
                <Row>
                    <Modal
                        maskClosable={false}
                        visible={this.state.editVisible}
                        editConfirmLoading={this.state.editConfirmLoading}
                        title="选择车牌号"
                        wrapClassName="vertical-center-modal"
                        width="600px"
                        onCancel={() => this.setModalVisible(false)}
                        footer={[
                            <Button key="back" type='default' onClick={() => {
                                this.setModalVisible(false)
                            }}>取消</Button>,
                            <Button key="submit" type="primary" onClick={() => {
                                this.clickOk()
                            }}>确定</Button>
                        ]}
                    >
                    <div className="clearfix">
                        {
                            this.state.roleData.map((item, index) => {
                                return (
                                    <span key={index}
                                          className={this.state.is_choose == index ? "roleItem1" : "roleItem"}
                                          onClick={() => this.chooseRole(index)}>
                                        {item.vehicle_num}
                                    </span>
                                )
                            })
                        }
                    </div>
                </Modal>
                </Row>
            </span>
        )
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    setModalVisible(visible) {
        if (visible) {
            this.handleGetCarList();
        }
        this.setState({
            editVisible: visible
        })
    };

    /**
     * 获取车辆列表
     */
    handleGetCarList() {
        app.post(user.GET_ALLVEHICLE, {}).then((result) => {
            if (result.code === 1) {
                let roleData = result.data.dataSet;
                let data = [];
                for (let i = 0; i < roleData.length; i++) {
                    let item = {};
                    item.vehicle_num = roleData[i].vehicle_num;
                    data.push(item);
                }
                this.setState({roleData: data});
            } else {
                this.setState({roleData: []})
            }
        })
    }

    /**
     * 处理选择车辆事件
     * @param index
     */
    chooseRole(index) {
        this.setState({is_choose: index});
        let chooseData = this.state.roleData[index];
        this.setState({chooseData: chooseData})
    };

    /**
     * 确定选择
     */
    clickOk() {
        let data = this.state.chooseData;
        this.props.choose(data);
        this.setState({
            editVisible: false
        })
    }
};
const ChooseCars = Form.create()(ChooseCar);

class Search extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '',
        }
    };

    render() {
        return (
            <div className="searchContainer">
                <Icon className="searchLogo" type="search"/>
                <Input className='searchInput' placeholder={this.props.type} style={{
                    height: '28px',
                    width: '80%',
                    paddingLeft: '30px',
                    backgroundColor: '#f1f1f1',
                    border: 'none',
                    paddingTop: '14px',
                    paddingBottom: '14px',
                    paddingRight: '23px'
                }} onChange={(e) => this.handleOnChange(e)}/>
                <span className="searchCancel" onClick={() => this.handleSearch()}>搜索</span>
            </div>
        )
    };

    /**
     * 处理输入框变化事件
     * @param e
     */
    handleOnChange(e) {
        this.setState({value: e.target.value});
    };

    /**
     * 处理搜索按钮事件
     */
    handleSearch() {
        let value = this.state.value;
        if (value == undefined || value.length <= 0) {
            app.alert('请输入搜索条件', 'error', 3);
            return;
        }
        this.props.handleSearchData(this.state.value);
    }
}

class Back extends Component {
    constructor(props) {
        super(props);
        this.state = {
            real_pay: 0,
        }
    }

    render() {
        const back = this.props.back;
        return (
            <div className="backContainer">
                {
                    back === "true" ? <div className="logoContainer" onClick={() => this.handleBack()}>
                    <span className="logoBack">
                        <Icon type="left"/>
                    </span>
                        <span className="fontBack">
                        返回
                    </span>
                    </div> : <div></div>
                }
                {this.props.title}
            </div>
        )
    }

    /**
     * 处理返回事件
     */
    handleBack() {
        this.props.click();
    }
}

//客户页面头部组件
class Head extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        const back = this.props.back;
        const backTitle = this.props.backTitle;
        return (
            <div className="backContainer">
                {
                    back === "true" ?
                        <div className="logoContainer" onClick={() => this.handleBack()}>
                            <span className="logoBack">
                                <Icon type="left"/>
                            </span>
                            <span className="fontBack">
                                {backTitle}
                            </span>
                        </div> :
                        <div className="headSearchContainer">
                            <span className="headLogoBack" onClick={() => this.handleBack()}>
                                <Icon type="left"/>
                            </span>
                            <div className="headInputContainer">
                                <Icon className="headSearchLogo" type="search"/>
                                <Input type={'text'} className='headSearchInput' placeholder={this.props.type}
                                       style={{
                                           height: '28px',
                                           width: '100%',
                                           backgroundColor: '#f1f1f1',
                                           border: 'none',
                                           paddingLeft: 26
                                       }} onChange={(e) => this.handleOnChange(e)}/>
                            </div>
                            <span className="headSearchCancel" onClick={() => this.handleSearch()}>搜索</span>
                        </div>
                }
            </div>
        )
    }

    /**
     * 处理返回事件
     */
    handleBack() {
        this.props.click();
    };

    /**
     * 处理输入框变化事件
     * @param e
     */
    handleOnChange(e) {
        this.setState({value: e.target.value});
    };

    /**
     * 处理搜索按钮事件
     */
    handleSearch() {
        let value = this.state.value;
        if (value == undefined || value.length <= 0) {
            app.alert('请输入搜索条件', 'error', 3);
            return;
        }
        this.props.handleSearchData(this.state.value);
    }
}

class ConfirmPay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editVisible: false,
            editConfirmLoading: false,
            imgUrl: '',
            real_pay: '',
            drawBack: '',
            imgData: []
        }
    }

    render() {
        const payMoney = this.props.money;
        const isPay = this.props.isPay;
        let btnTitle = '';
        if (isPay) {
            btnTitle = "确认";
        } else {
            btnTitle = "确认收款";
        }
        return (
            <span>
                <Button type='primary' onClick={() => this.setModalVisible(true)}
                        style={{width: '96%', marginLeft: '2%', height: '45px', fontSize: '18px'}}>{btnTitle}</Button>
                <Modal
                    maskClosable={true}
                    visible={this.state.editVisible}
                    editConfirmLoading={this.state.editConfirmLoading}
                    title={null}
                    wrapClassName="vertical-center-modal"
                    width="400px"
                    onCancel={() => this.setModalVisible(false)}
                    footer={false}
                    closable={false}
                >
                    <Row>
                        <Row className="actualMoney">拍照</Row>
                        <Row className="">
                            {
                                this.state.imgData.map((item, index) => {
                                    return (
                                        <ImgComponent key={index} imgUrl={item.imgUrl}
                                                      deleteImg={() => this.handleDeleteImg(index)}/>
                                    )
                                })
                            }
                            <Icon style={{fontSize: '80px'}} type="camera-o" onClick={() => this.handleCamera()}/>
                        </Row>
                        {
                            isPay === false ?
                                <span>
                                    <Row className="actualMoney">实际收款：</Row>
                        <Row className="needPayContent">
                            <span>
                                <img alt="null" src={money} style={{width: 18, height: 20}}/>
                            </span>
                            <span>
                                <input placeholder={'默认为' + payMoney} value={this.state.real_pay}
                                       onChange={(e) => this.handleOnRealPayChange(e)} className="needPayStyle"/>
                            </span>
                        </Row>
                        <Row className="actualMoney">退款金额：</Row>
                        <Row className="needPayContent">
                            <span>
                                <img alt="null" src={money} style={{width: 18, height: 20}}/>
                            </span>
                            <span>
                                <input placeholder={'默认为' + 0.00} value={this.state.drawBack}
                                       onChange={(e) => this.handleOnDrawBackChange(e)} className="needPayStyle"/>
                            </span>
                        </Row>
                            </span> : ''
                        }
                        <Row style={{marginTop: '15px'}}>
                            <Button type='primary' onClick={() => this.handleConfirmPay()}
                                    style={{width: '100%', height: '45px', fontSize: '18px'}}>{btnTitle}</Button>
                        </Row>
                    </Row>
                </Modal>
            </span>
        )
    }

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    setModalVisible(visible) {
        this.setState({editVisible: visible});
    }

    /**
     * 调用微信js接口 处理拍照事件
     */
    handleCamera() {
        const _this = this;
        window.wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                _this.handleUploadWx(localIds);
            }
        });
    };

    /**
     * 调用微信js接口 将图片上传到微信
     * @param localIds
     */
    handleUploadWx(localIds) {
        const _this = this;
        window.wx.uploadImage({
            localId: localIds.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                var serverId = res.serverId; // 返回图片的服务器端ID
                _this.handleUpload(serverId);
            }
        });
    }

    /**
     * 根据从微信返回的serverId 下载图片并获取url
     * @param serverId
     * @returns {Promise.<void>}
     */
    async handleUpload(serverId) {
        const _this = this;
        let result = await app.post(wechat.UPLOAD_IMAGE, {serverId: serverId});
        if (result.code === 1) {
            let url = result.data.url;
            let imgData = _this.state.imgData;
            imgData.push({imgUrl: url});
            _this.setState({imgData});
        } else {
            app.alert(result.msg, 'error', 3);
        }
    };

    /**
     * 处理司机收款输入框变化事件
     * @param e
     */
    handleOnRealPayChange(e) {
        this.setState({real_pay: e.target.value});
    };

    /**
     * 处理退出输入框变化事件
     * @param e
     */
    handleOnDrawBackChange(e) {
        this.setState({drawBack: e.target.value});
    }

    /**
     * 处理完成订单事件
     * @returns {Promise.<void>}
     */
    async handleConfirmPay() {
        let employee_id = app.getData('employee_id');
        let output_id = this.props.output_id;
        let output_driver_money = this.state.real_pay;
        let output_back_money = this.state.drawBack;
        let imgData = this.state.imgData;
        if (output_driver_money == null || output_driver_money == undefined || output_driver_money.length <= 0) {
            output_driver_money = this.props.money;
        }
        if (output_back_money == null || output_back_money == undefined || output_back_money.length <= 0) {
            output_back_money = 0;
        }
        if (imgData == null || imgData == undefined || imgData.length <= 0) {
            app.alert('请拍照');
            return;
        }
        let output_finish_photo = '';
        for (let i = 0; i < imgData.length; i++) {
            output_finish_photo = output_finish_photo + imgData[i].imgUrl + ',';
        }
        if (output_finish_photo.length > 0) {
            output_finish_photo = output_finish_photo.substr(0, output_finish_photo.length - 1);
        }
        let data = {
            employee_id: employee_id,
            output_id: output_id,
            output_driver_money: output_driver_money,
            output_back_money: output_back_money,
            output_finish_photo: output_finish_photo
        };
        let result = await app.post(order.CONFIRM_SENDOUTPUT, data);
        if (result.code === 1) {
            app.alert('订单完成', 'success', 2);
            this.setModalVisible(false);
            this.props.handleRefresh();
        } else {
            app.alert(result.msg, 'error', 3);
        }
    };

    /**
     * 删除图片
     * @param index
     */
    handleDeleteImg(index) {
        let imgData = this.state.imgData;
        imgData.splice(index, 1);
        this.setState({imgData});
    }
}

class LogisticsConfirmPay extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editVisible: false,
            editConfirmLoading: false,
            imgUrl: '',
            output_pay: '',
            imgData: [],
            output_check_num: '',
            output_remark: '',
        }
    }

    render() {
        const payMoney = this.props.money;
        return (
            <span>
                <Button type='primary' onClick={() => this.setModalVisible(true)}
                        style={{width: '96%', marginLeft: '2%', height: '45px', fontSize: '18px'}}>{"完成配送"}</Button>
                <Modal
                    maskClosable={true}
                    visible={this.state.editVisible}
                    editConfirmLoading={this.state.editConfirmLoading}
                    title={null}
                    wrapClassName="vertical-center-modal"
                    width="400px"
                    onCancel={() => this.setModalVisible(false)}
                    footer={false}
                    closable={false}
                >
                    <Row>
                        <Row className="actualMoney">拍照</Row>
                        <Row className="">
                            {
                                this.state.imgData.map((item, index) => {
                                    return (
                                        <ImgComponent key={index} imgUrl={item.imgUrl}
                                                      deleteImg={() => this.handleDeleteImg(index)}/>
                                    )
                                })
                            }
                            <Icon style={{fontSize: '80px'}} type="camera-o" onClick={() => this.handleCamera()}/>
                        </Row>
                        <Row className="actualMoney">托运费用：</Row>
                        <Row className="needPayContent">
                            <span>
                                <img alt="null" src={money} style={{width: 18, height: 20}}/>
                            </span>
                            <span>
                                <input placeholder={'请输入'} value={this.state.output_pay}
                                       onChange={(e) => this.handleOnDrawBackChange(e)} className="needPayStyle"/>
                            </span>
                        </Row>
                        <Row style={{marginTop: '5px'}}>
                            <Col span={24} className="actualMoney">托运单号：</Col>
                            <Col span={24}><input value={this.state.output_check_num} placeholder="请输入"
                                                  onChange={(e) => this.handleOutputCheckChange(e)}
                                                  className="needPayStyleLogistics"/>
                            </Col>
                        </Row>
                        <Row style={{marginTop: '5px'}}>
                            <Col span={24} className="actualMoney">备注：</Col>
                            <Col span={24}><input value={this.state.output_remark} placeholder="请输入"
                                                  onChange={(e) => this.handleRemarkChange(e)}
                                                  className="needPayStyleLogistics"/>
                            </Col>
                        </Row>
                        <Row style={{marginTop: '15px'}}>
                            <Button type='primary' onClick={() => this.handleConfirmPay()}
                                    style={{width: '100%', height: '45px', fontSize: '18px'}}>{"完成配送"}</Button>
                        </Row>
                    </Row>
                </Modal>
            </span>
        )
    }

    /**
     * 处理物流公司名变化事件
     */
    handleOutputCheckChange(e) {
        this.setState({output_check_num: e.target.value});
    };

    /**
     * 处理物流公司电话变化事件
     */
    handleRemarkChange(e) {
        this.setState({output_remark: e.target.value});
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    setModalVisible(visible) {
        this.setState({editVisible: visible});
    }

    /**
     * 调用微信js接口 处理拍照事件
     */
    handleCamera() {
        const _this = this;
        window.wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                _this.handleUploadWx(localIds);
            }
        });
    };

    /**
     * 调用微信js接口 将图片上传到微信
     * @param localIds
     */
    handleUploadWx(localIds) {
        const _this = this;
        window.wx.uploadImage({
            localId: localIds.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
                let serverId = res.serverId; // 返回图片的服务器端ID
                _this.handleUpload(serverId);
            }
        });
    }

    /**
     * 根据从微信返回的serverId 下载图片并获取url
     * @param serverId
     * @returns {Promise.<void>}
     */
    async handleUpload(serverId) {
        const _this = this;
        let result = await app.post(wechat.UPLOAD_IMAGE, {serverId: serverId});
        if (result.code === 1) {
            let url = result.data.url;
            let imgData = _this.state.imgData;
            imgData.push({imgUrl: url});
            _this.setState({imgData});
        } else {
            app.alert(result.msg, 'error', 3);
        }
    };

    /**
     * 处理退出输入框变化事件
     * @param e
     */
    handleOnDrawBackChange(e) {
        this.setState({output_pay: e.target.value});
    }

    /**
     * 处理完成订单事件
     * @returns {Promise.<void>}
     */
    async handleConfirmPay() {
        let employee_id = app.getData('employee_id');
        let output_id = this.props.output_id;
        let output_pay = this.state.output_pay;
        let output_check_num = this.state.output_check_num;
        let output_remark = this.state.output_remark;
        let imgData = this.state.imgData;
        if (!output_pay) {
            output_pay = this.props.money;
        }
        if (imgData == null || imgData == undefined || imgData.length <= 0) {
            app.alert('请拍照');
            return;
        }
        if (!output_check_num) {
            app.alert('输入托运单号');
            return;
        }
        let output_finish_photo = '';
        for (let i = 0; i < imgData.length; i++) {
            output_finish_photo = output_finish_photo + imgData[i].imgUrl + ',';
        }
        if (output_finish_photo.length > 0) {
            output_finish_photo = output_finish_photo.substr(0, output_finish_photo.length - 1);
        }
        let data = {
            employee_id: employee_id,
            output_id: output_id,
            output_pay: output_pay,
            output_check_num: output_check_num,
            output_remark: output_remark,
            output_finish_photo: output_finish_photo
        };
        let result = await app.post(order.CONFIRM_SENDCHECKOUTPUT, data);
        if (result.code === 1) {
            app.alert('订单完成', 'success', 2);
            this.setModalVisible(false);
            this.props.handleRefresh();
        } else {
            app.alert(result.msg, 'error', 3);
        }
    };

    /**
     * 删除图片
     * @param index
     */
    handleDeleteImg(index) {
        let imgData = this.state.imgData;
        imgData.splice(index, 1);
        this.setState({imgData});
    }
}

class ImgComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    render() {
        return (
            <div style={{position: 'relative'}} className="imgItem">
                <Icon type="close" style={{position: 'absolute', left: '76px', top: -2}}
                      onClick={() => this.deleteImg()}/>
                <img alt="照片" src={config.imgServerUrl + this.props.imgUrl}
                     style={{width: '100%', height: '100%'}}/>
            </div>
        )
    };

    /**
     * 处理删除图片事件
     */
    deleteImg() {
        this.props.deleteImg();
    }
}

class ShowImg extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editVisible: false,
            imgUrl: '',
        }
    }

    render() {
        return (
            <span>
                <div style={{
                    width: 80,
                    height: 80,
                    background: '#cccccc',
                    float: 'left',
                    marginLeft: '10px',
                    padding: 5
                }} onClick={() => this.setModalVisible(true)}>
                    <img style={{height: '100%', width: '100%'}} src={this.props.imgUrl}/>
                </div>
                <Modal
                    maskClosable={true}
                    visible={this.state.editVisible}
                    title={'查看图片'}
                    wrapClassName="vertical-center-modal"
                    width="100%"
                    onCancel={() => this.setModalVisible(false)}
                    footer={false}
                    closable={false}
                >
                    <Row>
                       <img style={{width: '100%', height: '364px'}} src={this.props.imgUrl}/>
                    </Row>
                </Modal>
            </span>
        )
    };

    /**
     * 显示和隐藏弹框
     * @param visible
     */
    setModalVisible(visible) {
        this.setState({editVisible: visible});
    }
}

export {
    Search,
    Back,
    Head,
    ConfirmPay,
    LogisticsConfirmPay,
    ChooseXhs,//选择跟车人
    ChooseCars,//选择车牌号
    ShowImg,//显示图片
}